package cn.talk.socket.service;

import java.io.ObjectInputStream;
import java.net.Socket;

public class Service_Listen implements Runnable {

    Socket socket;
    Service service;
    String id;
    String sourceId = null;
    String sendId = null;

    public Service_Listen(Socket socket, String id, Service s) {
        this.socket = socket;
        this.id = id;
        this.service = s;
    }

    @Override
    public void run() {

        try {
            service.send("service", "restId-" + id, id);
            while (true) {
                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                String mes = (String) ois.readObject();
                System.out.println("收到的信息为：" + mes);
                String[] strings = mes.split("-");
                sourceId = strings[0];
                String message = strings[1];
                sendId = strings[2];
                if(message.equals("loginOut")){
                    service.out(sourceId);
                }else {
                    service.send(sourceId, message, sendId);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
